const express = require("express");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const path = require("path");
const serveIndex = require("serve-index");
const app = express();
const config = require("./webpack/webpack.dev.js");
const compiler = webpack(config);
const appConfig = require("./app.config.js");
// 告知 express 使用 webpack-dev-middleware，
// 以及将 webpack.config.js 配置文件作为基础配置。通过webpackDevMiddleware把开发环境打包的内容写入硬盘
app.use(
  webpackDevMiddleware(compiler, {
    // publicPath: config.output.publicPath,
    publicPath: "/",
    index: true,
    mimeTypes: { phtml: "text/html" },
    serverSideRender: true,
    writeToDisk: true,
  })
);
//配置与后端本地调试需要加isv
app.use("/isv", express.static(path.join(__dirname, "./cache")));
app.use("/isv", serveIndex(path.join(__dirname, "./cache"), { icons: true }));
app.all("*", function (req, res, next) {
  // 设置可以跨域访问的域名，将其设置为本地苍穹服务访问地址
  res.header("Access-Control-Allow-Origin", appConfig.COSMIC_SERVER_URL);
  res.header("Access-Control-Allow-Credentials", true);
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
  );
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header(
    "Content-Type",
    "text/css;text/javascript;text/html;application/json;application/x-img"
  );
  next();
});

// 将文件 serve 到 port 3000。
app.listen(appConfig.DEV_CACHE_PORT, function () {
  console.log("Example app listening on port }!\n"+appConfig.DEV_CACHE_PORT);
});
